package edu.biwu.cookie05;

import edu.biwu.utils.CookieUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
 * 记录上次访问时间案例
 */
@WebServlet("/lastVisited")
public class LastVisited extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        //1.查找一个名称为lastVisited的cookie
        Cookie[] cookies = request.getCookies();
        Cookie cookie = CookieUtils.getCookie(cookies, "lastVisited");

        if (cookie == null) {
            //向浏览器响应 "欢迎第一次访问"
            response.getWriter().write("欢迎第一次访问");
        } else {
            //说明不是第一次访问，向浏览器写入上次访问的时间
            //将取出内容进行解码并响应给浏览器
            String decodeDate = URLDecoder.decode(cookie.getValue(), "UTF-8");
            response.getWriter().write("您上次访问时间为：" + decodeDate);
        }

        //无论是第一次,第二次,第三次,....第n次访问,都需要将当前系统时间设置到cookie,响应给浏览器
        String dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());

        //在放入cookie之前，先进行编码，防止cookie不支持某些字符
        String encodeDate = URLEncoder.encode(dateFormat, "UTF-8");

        Cookie lastVisitedCookie = new Cookie("lastVisited", encodeDate);
        lastVisitedCookie.setMaxAge(7 * 24 * 60 * 60);
        lastVisitedCookie.setPath(request.getContextPath());
        response.addCookie(lastVisitedCookie);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
